package com.zhengke.controller.spxxgl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.zhengke.common.object.ZTreeNode;
import com.zhengke.common.util.DateUtil;
import com.zhengke.common.util.FastDFSUtils;
import com.zhengke.common.util.FastDfsApiOpr;
import com.zhengke.common.util.LoadProperties;
import com.zhengke.pojo.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhengke.common.object.AjaxDone;
import com.zhengke.common.object.Result;
import com.zhengke.service.spxxgl.GoodsDetailService;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 创建时间：2019年12月26日 下午7:46:36
 * <p>
 * 项目名称：tvmallbs
 *
 * @author 王东科
 * @version 1.0
 * <p>
 * 文件名称：GoodsDetailController.java
 * <p>
 * 类说明：
 */

@Controller
@RequestMapping("goodsDetail/")
public class GoodsDetailController {

    @Autowired
    private GoodsDetailService service;

    /**
     * 到商品信息管理页面
     */
    @RequestMapping("toGoodsDetail.do")
    public String toGoodsDetail() {
        return "goodsDetail/goodsDetailMgr";
    }

    /**
     * 商品信息列表
     *
     * @param goodsName
     * @param gc1
     * @param gc2
     * @param gc3
     * @param status
     * @param brandName
     * @param isNormal
     * @param integralBuy
     * @param page
     * @param limit
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list.do", method = RequestMethod.POST)
    public Result list(String goodsName, String gc1, String gc2, String gc3, String status,
                       String brandName, String isNormal, String integralBuy, int page, int limit) {
        Result rs = null;
        try {
            rs = service.queryGoodsDetail(goodsName, gc1, gc2, gc3, status, brandName, isNormal, integralBuy, page, limit);
            return rs;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result();
    }

    /**
     * 上下架商品
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("updateStatu.do")
    public AjaxDone updateStatu(HttpServletRequest request) {
        String sta = request.getParameter("status");
        String gd = request.getParameter("goodsId");

        Integer status = new Integer(sta.equals("0") ? "1" : "0");
        Integer goodsId = new Integer(gd);
        GoodsDetail goodsDetail = new GoodsDetail();
        goodsDetail.setGoodsId(goodsId);
        goodsDetail.setStatus(status);
        try {
            service.updateStatus(goodsDetail);
            return new AjaxDone("200", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "修改失败");
    }

    /**
     * 跳转到图片编辑页面
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("toPicsPage.do")
    public String updatePics(HttpServletRequest request, ModelMap model) {
        String goodsId = request.getParameter("goodsId");
        model.put("goodsId", goodsId);
        String fileServerUrl = null;
        List<GoodImages> imagesList = null;
        try {
            fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            imagesList = service.queryImages(goodsId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (GoodImages images : imagesList) {

            String infoPicPath = images.getInfoPicPath();
            String thumbPicPath = images.getThumbPicPath();
            String picPath1 = images.getPicPath1();
            String picPath2 = images.getPicPath2();
            String picPath3 = images.getPicPath3();
            String picPath4 = images.getPicPath4();
            String picPath5 = images.getPicPath5();
            if (!"".equals(picPath1) && picPath1 != null) {
                picPath1 = fileServerUrl + picPath1;
            }
            if (!"".equals(picPath2) && picPath2 != null) {
                picPath2 = fileServerUrl + picPath2;
            }
            if (!"".equals(picPath3) && picPath3 != null) {
                picPath3 = fileServerUrl + picPath3;
            }
            if (!"".equals(picPath4) && picPath4 != null) {
                picPath4 = fileServerUrl + picPath4;
            }
            if (!"".equals(picPath5) && picPath5 != null) {
                picPath5 = fileServerUrl + picPath5;
            }
            if (!"".equals(thumbPicPath) && thumbPicPath != null) {
                thumbPicPath = fileServerUrl + thumbPicPath;
            }
            if (!"".equals(infoPicPath) && infoPicPath != null) {
                infoPicPath = fileServerUrl + infoPicPath;
            }

            model.put("picPath1", picPath1);
            model.put("picPath2", picPath2);
            model.put("picPath3", picPath3);
            model.put("picPath4", picPath4);
            model.put("picPath5", picPath5);
            model.put("infoPicPath", infoPicPath);
            model.put("thumbPicPath", thumbPicPath);
        }
        return "goodsDetail/toUpdatePics";
    }


    /**
     * 上传图片(单张)
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadPic.do")
    public Object UploadPictures(@RequestParam CommonsMultipartFile file) {
        try {
            String imageFileName = file.getOriginalFilename();
            String extName = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            if (file != null && !file.isEmpty()) {
                String path = LoadProperties.findValue("imgPath") + "/" + DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + "." + extName;
                File file1 = new File(path);
                if (!file1.getParentFile().exists()) {
                    file1.getParentFile().mkdirs();
                }
                FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
                //上传fastDFS后图片完整地址
                String file_id = FastDfsApiOpr.upload(file1.getPath(), extName);
                //读取config.properties查找访问路径的ip+端口
                String rtnPath = LoadProperties.findValue("FILE_SERVER_URL") + file_id;
                //String rtnPath = LoadProperties.findValue("viewUrl")+"?path="+file1.getPath();
                if (file1 != null) {
                    file1.delete();
                }
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("src", rtnPath);
                ReturnAjax ra = new ReturnAjax();
                ra.setData(data);
                ra.setMsg("成功");
                ra.setCode("0");
                return ra;
            } else {
                return new ReturnAjax("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnAjax("300", "上传失败");
    }

    /**
     * 跳转到编辑详情图图片页面(单张图片)
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping("toEditInfoPicPage.do")
    public String toEditPicsPage(HttpServletRequest request, ModelMap map) {
        String infoPicPath = request.getParameter("infoPicPath");
        String goodsId = request.getParameter("goodsId");
        map.put("infoPicPath", infoPicPath);
        map.put("goodsId", goodsId);
        return "goodsDetail/editInfoPic";
    }


    /**
     * 保存图片修改(单张)
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("updatePic.do")
    public AjaxDone updatePic(HttpServletRequest request) {

        String goodsId = request.getParameter("goodsId");
        String picpath1 = request.getParameter("picpath1");
        String picpath2 = request.getParameter("picpath2");
        String mark = request.getParameter("mark");
        try {
            String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            GoodImages images = new GoodImages();
            if (!"".equals(goodsId) && goodsId != null) {
                images.setGoodsId(goodsId);
            }

            if (!"".equals(mark) && mark != null && "thumbPic".equals(mark)) {
                if (!"".equals(picpath2) && picpath2 != null) {
                    images.setThumbPicPath(picpath2.replace(fileServerUrl, ""));
                }

            } else if (!"".equals(mark) && mark != null && "infoPic".equals(mark)) {
                if (!"".equals(picpath2) && picpath2 != null) {
                    images.setInfoPicPath(picpath2.replace(fileServerUrl, ""));
                }
            }
            int i = service.updateImages(images);
            if (i > 0) {
                Boolean exist = FastDFSUtils.isExist(picpath1);
                if (exist && !picpath1.equals(picpath2)) {
                    FastDfsApiOpr.deleteFile(picpath1.replace(fileServerUrl, ""));
                }
                return new AjaxDone("200", "上传成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统异常!");
    }

    /**
     * 跳转到轮播图编辑页面
     *
     * @return
     */
    @RequestMapping("toEditLunboPage")
    public String toEditLunboPage() {
        return "goodsDetail/editLunboPic";
    }

    /**
     * 上传多个文件(依次请求)
     * 直接修改数据库
     *
     * @param file
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("uploadLunboPics.do")
    public ReturnAjax uploadFiles(@RequestParam CommonsMultipartFile file, @RequestParam String goodsId) throws Exception {
        ReturnAjax ra = new ReturnAjax();

        String imageFileName = file.getOriginalFilename();
        String extName = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);

        if (file != null && !file.isEmpty()) {
            String path = LoadProperties.findValue("imgPath") + "/" + DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + "." + extName;
            File file1 = new File(path);
            if (!file1.getParentFile().exists()) {
                file1.getParentFile().mkdirs();
            }
            FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
            //上传fastDFS后图片完整地址
            String file_id = FastDfsApiOpr.upload(file1.getPath(), extName);
            //读取config.properties查找访问路径的ip+端口
            String rtnPath = LoadProperties.findValue("FILE_SERVER_URL") + file_id;
            //String rtnPath = LoadProperties.findValue("viewUrl")+"?path="+file1.getPath();
            if (file1 != null) {
                file1.delete();
            }

            List<GoodImages> imagesList = service.queryImages(goodsId);
            int i = 0;
            if (null != file_id && !file_id.isEmpty()) {
                for (GoodImages images : imagesList) {
                    String picPath1 = LoadProperties.findValue("FILE_SERVER_URL") + images.getPicPath1();
                    if (FastDFSUtils.isExist(picPath1)) {
                        FastDfsApiOpr.deleteFile(images.getPicPath1());
                    }
                    images.setPicPath1(images.getPicPath2());
                    images.setPicPath2(images.getPicPath3());
                    images.setPicPath3(images.getPicPath4());
                    images.setPicPath4(images.getPicPath5());
                    images.setPicPath5(file_id);
                    images.setGoodsId(images.getGoodsId());
                    i = service.updateImages(images);
                }
            }
            if (i > 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("data", rtnPath);
                ra.setCode("200");
                ra.setMsg("上传成功");
                ra.setData(data);
                return ra;
            }
        }
        return new ReturnAjax("300", "上传失败", null);
    }

    /**
     * 删除商品信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteGoodsDetail.do")
    public AjaxDone deleteGoodsDetail(HttpServletRequest request) {
        String goodsId = request.getParameter("goodsId");
        try {
            Integer i = service.deleteGoodsDetail(Integer.parseInt(goodsId));
            if (i <= 0) {
                return new AjaxDone("300", "请求失败");
            }
            return new AjaxDone("200", "请求成功");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return new AjaxDone("300", "请求失败");
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxDone("300", "请求失败");
        }
    }

    /**
     * 查询商品所属分类
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "querySysBy.do", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String querySysBy(HttpServletRequest request) {
        String gcParentId = request.getParameter("gcParentId");

        List<SysGoods> list = new ArrayList<SysGoods>();
        try {
            if (gcParentId != null && gcParentId != "") {
                int gcID = Integer.parseInt(gcParentId);
                list = service.querySys(gcID);
            } else {
                return "200";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = JSON.toJSONString(list);

        System.out.println(json);
        return json;
    }
}
